package com.example.ffepeg.ffeImg;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


/***
 *  根据视频的大小自定义视频水印的尺寸
 */
@Slf4j
public class videoFfmpegTest {

    // https://aigc-files.bigmodel.cn/api/cogvideo/2f583f40-fe63-11ef-ad3e-d2a032528fb8_cover_0.jpeg,
    // https://aigc-files.bigmodel.cn/api/cogvideo/2f6f75a2-fe63-11ef-a9a0-9ac3b4581a80_cover_0.jpeg
    // https://aigc-files.bigmodel.cn/api/cogvideo/2f583f40-fe63-11ef-ad3e-d2a032528fb8_0.mp4,
    // https://aigc-files.bigmodel.cn/api/cogvideo/2f6f75a2-fe63-11ef-a9a0-9ac3b4581a80_0.mp4

    public static void main(String[] args) throws Exception {
        String file = "https://aigc-files.bigmodel.cn/api/cogvideo/2f6f75a2-fe63-11ef-a9a0-9ac3b4581a80_0.mp4";
        String url = "https://aigc-files.bigmodel.cn/api/cogvideo/2f6f75a2-fe63-11ef-a9a0-9ac3b4581a80_cover_0.jpeg";
        String out = "src/main/resources/out/output12120202kk999.mp4";
        String logo = "https://pushimg.liecaizhijia.com/image_example/img/c6dd68e8-31da-4af8-b255-14082a279fff51826714613360d6ca65957966e675a.png";
        Map<String, Object> videoSizeMap = getVideoSize(url);
        Integer height = (int)videoSizeMap.get("height"); //视频高度
        Integer width = (int)videoSizeMap.get("width");  //视频宽度
        //目标比率
        double heightRatio = 0.05;
        //高度的取值
        int newWatermarkHeight = (int)(height * heightRatio);
        //宽度取值
        int TargetWidth = newWatermarkHeight * 3;
        //水印坐标的位置  10:微调值
        int intput_X = width - TargetWidth - 10;
        int intput_Y = height - newWatermarkHeight - 10;
        replaceLogo(file, out, intput_X, intput_Y, logo, TargetWidth, newWatermarkHeight);
    }

    private static boolean replaceLogo(String inputFile, String outputFile, int x, int y, String logoFile, int logoWidth, int logoHeight) {
        try {
            // 构建FFmpeg命令
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "ffmpeg", "-i", inputFile, "-i", logoFile,
                    "-filter_complex", "[1]scale=" + logoWidth + ":" + logoHeight + "[logo];[0][logo]overlay=" + x + ":" + y,
                    "-c:a", "copy",
                    "-threads", "2", // 添加线程数控制
                    outputFile
            );
            processBuilder.redirectErrorStream(true);
            // 启动进程
            Process process = processBuilder.start();
            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                // 可以选择在这里处理输出信息
                System.out.println(line);
            }
            // 等待进程完成
            int exitCode = process.waitFor();
            return exitCode == 0; // 如果退出码为0，则表示成功
        } catch (Exception e) {
            log.error("MP4替换水印失败!!!");
            e.printStackTrace();
        }
        return false;
    }

    private static Map<String,Object> getVideoSize(String img) {
        String path = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\output12120202.png";
        downloadFile(img, path);
        Map<String,Object> map = new HashMap<>();
        File file = new File(path);
        try {
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            log.info("图片宽度：" + width);
            log.info("图片高度：" + height);
            map.put("width", width);
            map.put("height", height);
        } catch (IOException e) {
            throw new RuntimeException("获取图片数据失败");
        }finally {
            deleteFileContent(path);
        }
        return map;
    }

    private static Boolean downloadFile(String fileURL, String savePath){
        try {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
                FileOutputStream out = new FileOutputStream(savePath);
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.close();
                in.close();
                log.info("保存路径: " + savePath);
                return true;
            } else {
                log.info("下载失败: " + responseCode);
            }
            //终止HTTP连接
            httpConn.disconnect();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败");
        }
        return false;
    }

    public static void deleteFileContent(String path) {
        File filePath = new File(path);
        // 检查文件是否存在且是一个文件而不是目录
        if (filePath.exists() && filePath.isFile()) {
            boolean isDeleted = filePath.delete();
            if (isDeleted) {
                System.out.println("文件删除成功");
            } else {
                System.out.println("文件删除失败");
            }
        } else if (!filePath.exists()) {
            System.out.println("文件不存在");
        } else {
            System.out.println("无法删除，指定路径是一个文件夹而非文件");
        }
    }

}
